<template>
    <div class="e-form">
        <BillTop title="大修计划编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.planRepair" label-width="200px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ formData.planRepair.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划日期：" prop="billDate">
                                            <el-date-picker
                                                v-model="formData.planRepair.billDate"
                                                type="date"
                                                placeholder="选择日期"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                                <span>{{ userInfo.orgInfo.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划人：">
                                                <span>{{ formData.planRepair.founderName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划维修费（元）：">
                                            <span>{{ onUpCollect() }}</span>
                                        </el-form-item>
                                    </el-col>
                                <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.planRepair.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="备注：">
                                        <el-input type="textarea" v-model="formData.planRepair.remarks"></el-input>
                                    </el-form-item>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon">
                        <div class="tabs-title" id="planDetail">计划明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="selectEquip">选择设备</el-button>
                                        <el-button  class="btn-delete"  @click="deletePlanList " v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planRepairDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planRepairDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column><el-table-column  prop="equipmentName" label="设备名称"  min-width="200"
                                    show-overflow-tooltip align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="productionNo"
                                    label="出厂编号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseDate"
                                    label="购置日期"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="repairCost"
                                    width="170"
                                    align="right"
                                    label="计划维修费用（元）"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.repairCost" clearable
                                        @input="curStateChange(row)"

                                         v-enter-float="{
                                            set: row,
                                            key: 'repairCost'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="cumulativeUsageTime"
                                    label="累计使用数（里程/小时）"
                                    width="200"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="repairContent"
                                    min-width="200"
                                    show-overflow-tooltip
                                    label="拟维修内容"
                                >
                                <template slot-scope="{ row }">
                                    <el-input v-model="row.repairContent" clearable @input="curStateChange(row)"></el-input>
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="changeHistoryCon">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button size="mini" class="btn-delete" v-if="isBatch[1].flag">删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('changeHistory')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[1].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                class="table"
                                ref="changeHistorySelect"
                                :data="changeHistoryTable"
                                border
                                @selection-change="changeHistoryTableSelect"
                                v-sortTable="{ 'tableData': changeHistoryTable, '_this': this, 'ref': 'changeHistorySelect' }"
                            >
                                <el-table-column type="selection" align="center" width="55" v-if="isBatch[1].flag">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{row}">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteHistory(row,$index)">
                                            </div>
                                        </div>
                                        <!-- <i
                                            id="iconEdit"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                            "
                                            class="el-icon-edit"
                                            @click="tableEdit(row.billId)"
                                        ></i> -->
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeBillNo"  align="center" label="变更编号" show-overflow-tooltip min-width="200" class-name="blue-column">
                                    <template slot-scope="{ row }" >
                                        <span @click="tableDbShow(row)">{{row.changeBillNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="变更日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="机构"
                                    show-overflow-tooltip
                                    min-width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="变更期数"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{row}">
                                        <span>{{statusLable(row.state)}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="5015"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.planRepair.state" @exas="exas" :founderId="formData.planRepair.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/equipPlan.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import count from '@/api/equip/equipPlanCount.js'
import requestAudit from '@/api/equip/common.js'
import { hideLoading, selectDataClient } from '@/utils/common'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //大修基础信息
                'planRepair': {
                    'auditTime': '',
                    'auditor': '',
                    'auditorId': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'budgetAmount': 0,
                    'changeBillId': '',
                    'changeBillNo': '',
                    'changeBudgetAmount': 0,
                    'changeState': 0,
                    'founderId': '',
                    'founderName': '',
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'number': 0,
                    'orgId': '',
                    'orgName': '',
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'state': 0,
                    'version': 0,
                    'workId': '',
                    'year': 0
                }
            },
            billid: this.$route.query.billid,
            planSelect: [], //计划明细选择项
            planRepairDtlList: [], //计划明细表格传后端
            planRepairDtlListCopy: [], //列表显示
            changeHistoryTable: [], //变更历史
            changeHistorySelect: [], //变更历史选择项
            auditHistoryTable: [],
            rules: {
                billDate: [
                    { required: true, message: '请选择日期', trigger: 'blur' },
                ],
            },
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 5015,  //配置计划
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 5015,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            currentRow: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj.label
            }
        },
        //当前单据状态
        state () {
            return this.formData.planRepair.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        onUpCollect () {
            return ()=>{
                this.formData.planRepair.budgetAmount = null
                return this.formData.planRepair.budgetAmount = count.onMajorUpCollect(this.planRepairDtlList)
            }
        },

    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        //ComExaButtons
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //是否进入批量管理
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'changeHistory':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //去变更新增页面
        handleChange () {
            const billid = this.billid
            this.$router.push({
                path: '/majorPlanChangeAdd',
                query: { billid }
            })
        },
        //变更查看页面
        tableDbShow (row) {
            if(row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/majorPlanChangeShow',
                    query: { billid: row.billId }
                })
            }else{
                this.auditParams.billId = row.billId
                requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                    this.auditState = res
                    if( this.auditState.canModify == true) {
                        this.$router.push({
                            path: '/majorPlanChangeEdit',
                            query: { billid: row.billId }
                        })
                    }else{
                        this.$router.push({
                            path: '/majorPlanChangeShow',
                            query: { billid: row.billId }
                        })
                    }
                })
            }
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getChangeHistory(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //基本信息查询
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.majorBaseInfo(params).then(res=>{
                this.formData.planRepair = res.planRepair
            })
        },
        //计划明细查询
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.majorPlanInfo(params).then(res=>{
                this.planRepairDtlListCopy = []
                this.planRepairDtlList = res.planRepairDtlList
                this.planRepairDtlList.map(item=>{
                    this.planRepairDtlListCopy.push(item)
                })
            })
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getMajorChangeHistory(params).then(res=>{
                this.changeHistoryTable = res.planRepairList
            })
        },
        getNowDate () {
            this.$set(
                this.formData,
                'applyTime',
                new Date()
                    .toLocaleDateString()
                    .replace(new RegExp('/', 'g'), '-')
            )
        },
        //选择设备
        selectEquip () {
            let ids = []
            ids = this.planRepairDtlListCopy.map(x=>x.accountId)
            selectDataClient({
                SelectServiceToken: '/facilityplan/list/account/equipment', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '选择设备' // 标题
            }).then(val => {
                this.setSelectedInfo(val)
                this.planRepairDtlList = this.planRepairDtlList ? this.planRepairDtlList : []
                this.planRepairDtlListCopy = this.planRepairDtlListCopy ? this.planRepairDtlListCopy : []
                val.forEach(item=>{
                    item.changeType = 1
                    let obj = {
                        'accountId': '',
                        'accountType': '',
                        'activeNo': '',
                        'billId': this.billid,
                        'billNo': '',
                        'categoryId': '',
                        'categoryName': '',
                        'changeType': 1,
                        'cumulativeUsageTime': null,
                        'equipmentId': '',
                        'equipmentName': '',
                        'equipmentNo': '',
                        'leasePlanId': '',
                        'manufacturer': '',
                        'oldState': 0,
                        'oneLevelCategoryId': '',
                        'oneLevelCategoryName': '',
                        'productionNo': '',
                        'purchaseDate': '',
                        'repairContent': '',
                        'repairCost': null,
                        'repairPlanDtlId': '',
                        'settledAmount': 0,
                        'specificationModel': '',
                        'state': 0,
                        'unit': '',
                        ...item
                    }
                    this.planRepairDtlList.push(obj)
                    this.planRepairDtlListCopy.push(obj)
                })
                this.itemObj = {}
                this.itemObjCopy = {}
                this.planRepairDtlListCopy = this.planRepairDtlListCopy.reduce((items, next)=>{
                    if(!this.itemObjCopy[next.accountId]) {
                        items.push(next)
                        this.itemObjCopy[next.accountId] = true
                    }
                    return items
                }, [])
                this.planRepairDtlList = this.planRepairDtlList.reduce((item, next)=>{
                    if(!this.itemObj[next.accountId]) {
                        item.push(next)
                        this.itemObj[next.accountId] = true
                    }
                    return item
                }, [])
            })
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //计划维修费用
        onAmount  () {
            this.onUpCollect()
        },
        //预算总金额 = 明细获取金额向上汇总
        // onUpCollect () {
        //     this.formData.planRepair.budgetAmount = null
        //     this.formData.planRepair.budgetAmount = count.onMajorUpCollect(this.planRepairDtlListCopy)
        //     console.log('dddffddd', this.planRepairDtlListCopy)
        // },
        //单个删除计划明细
        handleDelete (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    let length = this.errorMsg.length
                    if(row.repairPlanDtlId) {
                        this.$set(this.planRepairDtlList[$index], 'changeType', -1)
                        this.planRepairDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }else{
                        this.planRepairDtlList.splice($index, 1)
                        this.planRepairDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }
                }
            )
        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        //批量删除计划明细
        delete () {
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.repairPlanDtlId) {
                        this.$set(item, 'changeType', -1)
                        for(let i = this.planRepairDtlListCopy.length; i > 0; i--) {
                            if(this.planRepairDtlListCopy[i - 1] === item) {
                                this.planRepairDtlListCopy.splice(i - 1, 1)
                            }
                        }
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planRepairDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.planRepairDtlList[i - 1] === localArr[j]) {
                                    this.planRepairDtlList.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.planRepairDtlListCopy[i - 1] === localArr[j]) {
                                    this.planRepairDtlListCopy.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planRepairDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.repairCost === null || item.repairCost === '') {
                            let str = `请填写第 ${index + 1} 行的（计划维修费用）`
                            this.errorMsg.push(str)
                        }
                        if( +item.repairCost == 0) {
                            let str = `请填写第 ${index + 1} 行的（计划维修费用必须大于0）`
                            this.errorMsg.push(str)
                        }
                        if( item.repairContent === null || item.repairContent === '') {
                            let str = `请填写第 ${index + 1} 行的（拟维修内容）`
                            this.errorMsg.push(str)
                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }

            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.repairPlanDtlId) {
                if (row.changeType === 2) return
                this.currentRow.changeType = 2
            }
        },
        /*
            变更历史
        */
        //获取计划明细表格的选择项
        changeHistoryTableSelect (selection) {
            this.changeHistorySelect = selection
        },
        handleDeleteHistory (row) {
            let billids = [row.billId]
            request.majorPlanDelete(billids).then(()=>{
                this.init()
                this.clientPop('suc', '删除成功')
                this.$refs.changeHistorySelect.clearSelection()
            })
        },
        //删除草稿状态的变更历史
        handleChangeHistory () {
            const length = this.changeHistorySelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.changeHistorySelect.forEach(item=>{
                    if(item.state !== 0) {
                        this.clientPop(
                            'info',
                            '只要草稿状态才可以删除！',
                        )
                        this.$refs.changeHistorySelect.clearSelection()
                    }else{
                        this.clientPop(
                            'info',
                            this.moreDeleteErr(length),
                            this.deleteChangeHistory
                        )
                    }
                })
            }
        },
        //批量或单独删除变更历史
        deleteChangeHistory () {
            let billids = []
            this.changeHistorySelect.forEach(item=>{
                if(item.state === 0) {
                    billids.push(item.billId)
                    request.majorPlanDelete(billids).then(()=>{
                        this.init()
                        this.clientPop('suc', '删除成功')
                        this.$refs.changeHistorySelect.clearSelection()
                    })
                }
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updatemajorPlan(this.formData).then(()=>{
                    resolve()
                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    request.updateDtl(this.planRepairDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        this.setError('planDetail')
                        reject(err)
                        this.scorllError()
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.planRepairDtlListCopy.length === 0) {
                let str = '计划明细不能空！'
                this.errorMsg.push(str)
                this.setError('planDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl()
                ]
            }
            submitCommit(this, requestFn, 0)
        },
        //删除单据
        deleteBills () {
            let billids = [this.billid]
            request.majorPlanDelete(billids).then(()=>{
                this.clientPop('suc', '删除成功', this.handleClose)
            })
            // this.clientPop(
            //     'info',
            //     this.oneDeleteErr,
            //     ()=>{
            //         request.majorPlanDelete(billids).then(()=>{
            //             this.clientPop('suc', '删除成功', this.handleClose)
            //         })
            //     }
            // )
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
        },
        //取消
        handleClose () {
            this.$router.replace('/majorPlanList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
</style>
